﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository.Repositorys;
using Dora.Tools.Utility.Const;
using Dora.Tools.Utility;
using Microsoft.Extensions.Logging;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 微信小程序主题服务
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class OrgWxMPThemeService : DoraServiceBase, IOrgWxMPThemeService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly OrgWxMPThemeRepository _repository;
        private readonly OrganizationRepository _organizationRepository;
        private readonly OrgBigSettingRepository _orgbigsettingRepository;

        public OrgWxMPThemeService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _repository = new OrgWxMPThemeRepository(unitOfWork);
            _organizationRepository = new OrganizationRepository(unitOfWork);
            _orgbigsettingRepository = new OrgBigSettingRepository(unitOfWork);
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> Create(OrgWxMPThemeEntity entity)
        {
            entity.CreatedTime = DateTime.Now;
            var result = await _repository.InsertAsync(entity);
            return ResultDto<int>.Success(result.Id);

        }
        /// <summary>
        /// 根据主键获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<OrgWxMPThemeEntity> GetById(int id)
        {
            return await _repository.FirstOrDefaultAsync(id);
        }

        /// <summary>
        /// 根据主题值获取主题信息
        /// </summary>
        /// <param name="themeKey"></param>
        /// <returns></returns>
        public async Task<OrgWxMPThemeEntity> GetByKey(string themeKey)
        {
            var result = await _repository.FirstOrDefaultAsync(it => it.ThemeKey == themeKey && it.IsDeleted == 0);
            return result;
        }

        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<OrgWxMPThemeEntity>> GetPageList(OrgWxMPThemeQueryDto input)
        {
            var result = await _repository.GetPageList(input);
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> Update(OrgWxMPThemeEntity entity)
        {
            entity.UpdatedTime = DateTime.Now;
            var result = await _repository.UpdateAsync(entity);
            return result;
        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<OrgWxMPThemeEntity>> GetList(List<int> idList)
        {
            if (idList == null || idList.Count == 0)
            {
                return new List<OrgWxMPThemeEntity>();
            }
            var list = await _repository.GetAllListAsync(it => idList.Contains(it.Id));
            return list;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> Delete(OrgWxMPThemeEntity entity)
        {
            var result = false;
            //根据orgid获取当前绑定信息
            if (entity != null && entity.OrgId > 0)
            {
                var info = await _orgbigsettingRepository.FirstOrDefaultAsync(entity.OrgId);
                if (info != null)
                {
                    bool isUsing = info.WxMPTheme == entity.ThemeKey;
                    if (!isUsing)
                    {
                        result = await _repository.Delete(entity);
                    }
                    else
                    {
                        return new ResultDto<bool>(ResultCode.Fail, "无法删除绑定主题", false);
                    }
                }
            }
            return ResultDto<bool>.Success(result);
        }

        /// <summary>
        /// 根据组织结构ID批量添加信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> CreateByOrgIds(OrgWxThemeSaveDto input)
        {
            var num = 0;
            if (input == null || input.OrgIds == null || input.OrgIds?.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "没有需要创建的主题", 0);
            }
            //验证组织结构
            var orglist = await _organizationRepository.GetAllListAsync(it => input.OrgIds.Contains(it.Id));
            if (orglist == null || orglist.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "当前组织机构不存在", 0);
            }

            //验证是否KEY值已经存在
            var themeinfo = await GetByKey(input.ThemeName);
            if (themeinfo != null)
            {
                return new ResultDto<int>(ResultCode.Fail, "重复的主题Key", 0);
            }
            var ListThemeInfo = new List<OrgWxMPThemeEntity>();

            foreach (var item in orglist)
            {
                var info = new OrgWxMPThemeEntity();
                info.CreatedUserId = input.OpUserId;
                info.CreatedUserName = input.OpUserName;
                info.OrgId = item.Id;
                info.ThemeKey = input.ThemeKey;
                info.ThemeName = input.ThemeName;
                info.CreatedTime = DateTime.Now;
                ListThemeInfo.Add(info);
            }

            if (ListThemeInfo.Count > 0)
            {
                num = await _repository.CreateRange(ListThemeInfo);
            }
            return ResultDto<int>.Success(num);
        }

        /// <summary>
        /// 复制主题到某个组织机构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> CopyToOrg(OrgWxThemeCopyDto input)
        {
            var num = 0;
            if (input == null || input.ThemeIds == null || input.ThemeIds?.Count == 0)
            {
                return new ResultDto<int>(ResultCode.Fail, "没有需要复制的主题", 0);
            }
            //验证组织结构
            var orginfo = await _organizationRepository.FirstOrDefaultAsync(it => it.Id == input.OrgId);
            if (orginfo == null)
            {
                return new ResultDto<int>(ResultCode.Fail, "当前组织机构不存在", 0);
            }
            var arrLevelPath = ConvertHelper.StringToList<int>(orginfo.LevelPath, ',');
            if (arrLevelPath.Count < 1)
            {
                return new ResultDto<int>(ResultCode.Fail, "组织机构层级设置错误", 0);
            }

            //获取到orgId下的所有主题
            var existList = await GetListByOrgId(input.OrgId);
            //设置即将拷贝的主题集合
            var copythemeList = await GetList(input.ThemeIds);
            var newThemeList = new List<OrgWxMPThemeEntity>();

            foreach (var item in copythemeList)
            {
                var existItem = existList.Where(it => it.ThemeKey == item.ThemeKey).FirstOrDefault();
                if (existItem == null)
                {
                    item.OrgId = orginfo.Id;
                    item.CreatedTime = DateTime.Now;
                    item.CreatedUserId = input.OpUserId;
                    item.CreatedUserName = input.OpUserName;
                    newThemeList.Add(item);
                }
            }
            if (newThemeList.Count > 0)
            {
                num = await _repository.CreateRange(newThemeList);
            }
            return ResultDto<int>.Success(num);

        }

        /// <summary>
        /// 根据IdList获取列表
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<List<OrgWxMPThemeEntity>> GetListByOrgId(int OrgId)
        {
            var list = await _repository.GetAllListAsync(it => it.OrgId == OrgId && it.IsDeleted == 0);
            return list;
        }

        /// <summary>
        /// 设置为当前主题
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<bool>> SetOrgTheme(OrgSettingThemeSaveDto input)
        {
            var result = false;
            if (string.IsNullOrWhiteSpace(input.ThemeKey) || input.OrgId <= 0)
            {
                return new ResultDto<bool>(ResultCode.Fail, "请检查主题或组织机构", false);
            }
            var entity = await _orgbigsettingRepository.FirstOrDefaultAsync(input.OrgId);
            if (entity != null)
            {
                entity.UpdatedUserId = input.OpUserId;
                entity.UpdatedUserName = input.OpUserName;
                entity.WxMPTheme = input.ThemeKey;

                result = await _orgbigsettingRepository.UpdateThemeSetting(entity);
            }
            return ResultDto<bool>.Success(result);
        }
    }
}
